/********************************************************************************
 * Project Name		[JavaEE_Components]
 * File Name     	[CheckingMailsByPop3.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package javamail.mail;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import org.junit.Before;
import org.junit.Test;

import javamail.utils.MailConstants;
import javamail.utils.PasswordUtils;

/**
 * 使用POP3协议查看邮件
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class CheckingMailsByPop3 {

	private static Properties properties = null;

	private static String emailAddress = "javamail_sns@sina.com";

	@Before
	public void init() {
		properties = new Properties();
		properties.put("mail.store.protocol", MailConstants.PROTOCAL_POP3);
		properties.put("mail.pop3.host", MailConstants.POP3_HOST_OF_SINA);
		properties.put("mail.pop3.port", MailConstants.POP3_PORT_OF_SINA);
		properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED);
		properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED));
	}

	/**
	 * 使用POP3协议查看邮件并发送反馈
	 * 
	 * @throws Exception
	 */
	public static void checkMailsByPop3() throws Exception {
		// 创建Session对象并连接到指定的邮箱
		Session session = Session.getInstance(properties);
		Store store = session.getStore(MailConstants.PROTOCAL_POP3);
		store.connect(emailAddress, PasswordUtils.readPassword(emailAddress));

		// 获得收件箱
		Folder folder = store.getFolder("INBOX");
		// 以只读权限打开收件箱, 还可以配置为Folder.READ_WRITE
		folder.open(Folder.READ_ONLY);

		// POP3协议无法获知邮件的状态
		// getUnreadMessageCount得到的是收件箱的邮件总数,
		// getNewMessageCount和getDeletedMessageCount均为0
		System.out.println("一共有邮件" + folder.getMessageCount() + "封");
		System.out.println("新邮件有" + folder.getNewMessageCount() + "封");
		System.out.println("未读邮件有" + folder.getUnreadMessageCount() + "封");
		System.out.println("删除邮件有" + folder.getDeletedMessageCount() + "封");

		// 获得所有邮件
		Message[] messages = folder.getMessages();
		System.out.println("邮件数" + messages.length);

		folder.close(true);
		store.close();
	}

	@Test
	public void testCheckMailsByPop3() throws Exception {
		checkMailsByPop3();
	}
}
